<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-title">{{ appStore.appVersion }} 多端应用</view>
      <view class="navbar-right">
        <view class="network-status" :class="networkClass">
          {{ networkText }}
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y>
      <!-- 欢迎卡片 -->
      <view class="welcome-card">
        <view class="welcome-title">欢迎使用 uniapp 多端应用</view>
        <view class="welcome-subtitle">支持 Android、iOS、HarmonyOS</view>
        <view class="platform-info">
          <text>当前平台: {{ platformName }}</text>
          <text>系统版本: {{ systemVersion }}</text>
        </view>
      </view>

      <!-- 功能列表 -->
      <view class="feature-list">
        <view class="feature-title">功能特性</view>
        <view 
          class="feature-item" 
          v-for="feature in features" 
          :key="feature.id"
          @click="handleFeatureClick(feature)"
        >
          <view class="feature-icon">{{ feature.icon }}</view>
          <view class="feature-content">
            <view class="feature-name">{{ feature.name }}</view>
            <view class="feature-desc">{{ feature.description }}</view>
          </view>
          <view class="feature-arrow">></view>
        </view>
      </view>

      <!-- 系统信息 -->
      <view class="system-info" v-if="systemInfo">
        <view class="info-title">设备信息</view>
        <view class="info-grid">
          <view class="info-item">
            <text class="info-label">设备型号</text>
            <text class="info-value">{{ systemInfo.model }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">屏幕尺寸</text>
            <text class="info-value">{{ systemInfo.screenWidth }}x{{ systemInfo.screenHeight }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">像素比</text>
            <text class="info-value">{{ systemInfo.pixelRatio }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">状态栏高度</text>
            <text class="info-value">{{ systemInfo.statusBarHeight }}px</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部安全区域 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../store/app'
import { showToast, showConfirm } from '../../utils/common'
import Storage from '../../utils/storage'

const appStore = useAppStore()

// 状态栏高度
const statusBarHeight = computed(() => appStore.systemInfo?.statusBarHeight || 0)

// 系统信息
const systemInfo = computed(() => appStore.systemInfo)

// 平台名称
const platformName = computed(() => {
  const platform = systemInfo.value?.platform
  const platformMap: Record<string, string> = {
    'ios': 'iOS',
    'android': 'Android',
    'windows': 'Windows',
    'mac': 'macOS',
    'devtools': '开发工具'
  }
  return platformMap[platform || ''] || platform || '未知'
})

// 系统版本
const systemVersion = computed(() => systemInfo.value?.system || '未知')

// 网络状态
const networkClass = computed(() => {
  const type = appStore.networkType
  if (type === 'none') return 'network-offline'
  if (type === 'wifi') return 'network-wifi'
  return 'network-mobile'
})

const networkText = computed(() => {
  const type = appStore.networkType
  const networkMap: Record<string, string> = {
    'wifi': 'WiFi',
    '2g': '2G',
    '3g': '3G',
    '4g': '4G',
    '5g': '5G',
    'none': '无网络',
    'unknown': '未知'
  }
  return networkMap[type] || type
})

// 功能列表 - 大幅扩展
const features = ref([
  {
    id: 1,
    name: '网络请求',
    description: '封装的 axios 请求库，支持拦截器',
    icon: '🌐',
    status: 'active',
    action: 'testNetwork'
  },
  {
    id: 2,
    name: '状态管理',
    description: '使用 Pinia 进行状态管理',
    icon: '📦',
    status: 'active',
    action: 'showStore'
  },
  {
    id: 3,
    name: '本地存储',
    description: '支持过期时间的本地存储工具',
    icon: '💾',
    status: 'active',
    action: 'testStorage'
  },
  {
    id: 4,
    name: '设备信息',
    description: '获取设备型号、系统版本等信息',
    icon: '📱',
    status: 'active',
    action: 'showDeviceInfo'
  },
  {
    id: 5,
    name: '网络状态',
    description: '实时监控网络连接状态',
    icon: '📶',
    status: networkText.value === '无网络' ? 'offline' : 'online',
    action: 'checkNetwork'
  },
  {
    id: 6,
    name: '相机拍照',
    description: '调用系统相机进行拍照',
    icon: '📷',
    status: 'ready',
    action: 'takePhoto'
  },
  {
    id: 7,
    name: '选择图片',
    description: '从相册选择图片',
    icon: '🖼️',
    status: 'ready',
    action: 'chooseImage'
  },
  {
    id: 8,
    name: '扫码功能',
    description: '二维码/条形码扫描识别',
    icon: '📷',
    status: 'ready',
    action: 'scanCode'
  },
  {
    id: 9,
    name: '地理定位',
    description: '获取当前地理位置信息',
    icon: '📍',
    status: 'ready',
    action: 'getLocation'
  },
  {
    id: 10,
    name: '震动反馈',
    description: '设备震动和触觉反馈',
    icon: '📳',
    status: 'ready',
    action: 'vibrate'
  },
  {
    id: 11,
    name: '剪贴板',
    description: '读取和设置剪贴板内容',
    icon: '📋',
    status: 'ready',
    action: 'clipboard'
  },
  {
    id: 12,
    name: '屏幕亮度',
    description: '获取和设置屏幕亮度',
    icon: '🔆',
    status: 'ready',
    action: 'brightness'
  },
  {
    id: 13,
    name: '电池信息',
    description: '获取设备电池状态',
    icon: '🔋',
    status: 'ready',
    action: 'battery'
  },
  {
    id: 14,
    name: '文件操作',
    description: '文件读写、缓存管理',
    icon: '📁',
    status: 'ready',
    action: 'fileManager'
  },
  {
    id: 15,
    name: 'TypeScript',
    description: '完整的 TypeScript 支持',
    icon: '📝',
    status: 'active',
    action: 'showTypes'
  }
])

// 处理功能点击 - 根据不同功能执行不同操作
const handleFeatureClick = async (feature: any) => {
  switch (feature.action) {
    case 'testNetwork':
      await testNetworkRequest()
      break
    case 'showStore':
      showStoreInfo()
      break
    case 'testStorage':
      await testLocalStorage()
      break
    case 'showDeviceInfo':
      showDeviceDetails()
      break
    case 'checkNetwork':
      checkNetworkStatus()
      break
    case 'takePhoto':
      await takePhoto()
      break
    case 'chooseImage':
      await chooseImage()
      break
    case 'scanCode':
      await scanCode()
      break
    case 'getLocation':
      await getLocation()
      break
    case 'vibrate':
      vibrateDevice()
      break
    case 'clipboard':
      await testClipboard()
      break
    case 'brightness':
      await testBrightness()
      break
    case 'battery':
      await getBatteryInfo()
      break
    case 'fileManager':
      await testFileSystem()
      break
    case 'showTypes':
      showTypeScriptInfo()
      break
    default:
      showToast(`功能：${feature.name}`)
  }
}

// 测试网络请求
const testNetworkRequest = async () => {
  uni.showLoading({ title: '测试网络请求...' })
  try {
    // 模拟网络请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    uni.hideLoading()
    uni.showModal({
      title: '网络请求测试',
      content: '网络请求功能正常✅\n• 支持请求拦截器\n• 自动错误处理\n• Token自动携带\n• 响应数据统一格式化',
      showCancel: false
    })
  } catch (error) {
    uni.hideLoading()
    showToast('网络请求失败')
  }
}

// 显示状态管理信息
const showStoreInfo = () => {
  uni.showModal({
    title: 'Pinia 状态管理',
    content: `当前状态信息：\n• 应用版本：${appStore.appVersion}\n• 网络类型：${networkText.value}\n• 系统平台：${platformName.value}\n• 用户状态：${appStore.systemInfo ? '已获取设备信息' : '未初始化'}`,
    showCancel: false
  })
}

// 测试本地存储
const testLocalStorage = async () => {
  const testKey = 'demo_storage_test'
  const testData = {
    message: '这是测试数据',
    timestamp: Date.now(),
    platform: platformName.value
  }
  
  // 保存数据（30秒后过期）
  Storage.set(testKey, testData, 30)
  
  // 读取数据
  const savedData = Storage.get(testKey)
  
  // 获取存储信息
  const storageInfo = uni.getStorageInfoSync()
  
  uni.showModal({
    title: '本地存储测试',
    content: `存储功能测试✅\n• 数据已保存（30秒后过期）\n• 当前存储：${storageInfo.currentSize}KB\n• 存储上限：${storageInfo.limitSize}KB\n• 已存储${storageInfo.keys.length}个key`,
    showCancel: false
  })
}

// 显示设备详细信息
const showDeviceDetails = () => {
  const info = systemInfo.value
  if (!info) {
    showToast('设备信息未获取')
    return
  }
  
  uni.showModal({
    title: '设备详细信息',
    content: `📱 设备信息：\n• 品牌：${info.brand || '未知'}\n• 型号：${info.model}\n• 系统：${info.system}\n• 平台：${info.platform}\n• 版本：${info.version}\n\n📐 屏幕信息：\n• 尺寸：${info.screenWidth}×${info.screenHeight}px\n• 像素比：${info.pixelRatio}\n• 状态栏：${info.statusBarHeight}px`,
    showCancel: false
  })
}

// 检查网络状态
const checkNetworkStatus = () => {
  uni.getNetworkType({
    success: (res) => {
      const networkInfo = {
        'wifi': 'WiFi网络 📶',
        '2g': '2G网络 📶',
        '3g': '3G网络 📶', 
        '4g': '4G网络 📶',
        '5g': '5G网络 📶',
        'none': '无网络连接 ❌',
        'unknown': '网络类型未知 ⚠️'
      }
      
      uni.showModal({
        title: '网络状态检测',
        content: `当前网络：${networkInfo[res.networkType] || res.networkType}\n\n💡 网络监控功能：\n• 实时检测网络变化\n• 自动重连机制\n• 网络状态展示`,
        showCancel: false
      })
    }
  })
}

// 拍照功能
const takePhoto = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sourceType: ['camera']
    })
    
    uni.showModal({
      title: '拍照成功',
      content: `📷 拍照功能测试成功！\n• 图片路径：${res.tempFilePaths[0]}\n• 图片大小：${Math.round(res.tempFiles[0].size / 1024)}KB`,
      showCancel: false
    })
  } catch (error) {
    showToast('拍照失败或用户取消')
  }
}

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 3,
      sourceType: ['album']
    })
    
    uni.showModal({
      title: '选择图片成功',
      content: `🖼️ 已选择 ${res.tempFilePaths.length} 张图片\n• 支持多选（最多9张）\n• 自动压缩\n• 获取图片信息`,
      showCancel: false
    })
  } catch (error) {
    showToast('选择图片失败或用户取消')
  }
}

// 扫码功能
const scanCode = async () => {
  try {
    const res = await uni.scanCode({
      scanType: ['barCode', 'qrCode']
    })
    
    uni.showModal({
      title: '扫码成功',
      content: `📷 扫码结果：\n${res.result}\n\n• 支持二维码和条形码\n• 自动识别格式\n• 快速响应`,
      showCancel: false
    })
  } catch (error) {
    showToast('扫码失败或用户取消')
  }
}

// 获取地理位置
const getLocation = async () => {
  uni.showLoading({ title: '获取位置信息...' })
  try {
    const res = await uni.getLocation({
      type: 'gcj02'
    })
    uni.hideLoading()
    
    uni.showModal({
      title: '位置获取成功',
      content: `📍 当前位置：\n• 经度：${res.longitude.toFixed(6)}\n• 纬度：${res.latitude.toFixed(6)}\n• 精度：${res.accuracy}米\n• 海拔：${res.altitude || '未知'}米`,
      showCancel: false
    })
  } catch (error) {
    uni.hideLoading()
    showToast('位置获取失败，请检查权限设置')
  }
}

// 设备震动
const vibrateDevice = () => {
  uni.vibrateLong()
  showToast('设备震动测试 📳')
  
  setTimeout(() => {
    uni.vibrateShort()
    showToast('短震动反馈 ⚡')
  }, 1000)
}

// 测试剪贴板
const testClipboard = async () => {
  const testText = `UniApp多平台框架测试 - ${new Date().toLocaleTimeString()}`
  
  try {
    await uni.setClipboardData({
      data: testText
    })
    
    const clipboardData = await uni.getClipboardData()
    
    uni.showModal({
      title: '剪贴板测试',
      content: `📋 剪贴板功能测试成功！\n\n已复制内容：\n${clipboardData.data}\n\n• 支持文本复制粘贴\n• 跨应用数据共享`,
      showCancel: false
    })
  } catch (error) {
    showToast('剪贴板操作失败')
  }
}

// 测试屏幕亮度
const testBrightness = async () => {
  try {
    const res = await uni.getScreenBrightness()
    
    uni.showModal({
      title: '屏幕亮度信息',
      content: `🔆 当前屏幕亮度：${Math.round(res.value * 100)}%\n\n• 获取当前亮度值\n• 动态调节亮度\n• 适配不同环境`,
      showCancel: false
    })
  } catch (error) {
    showToast('获取屏幕亮度失败')
  }
}

// 获取电池信息
const getBatteryInfo = async () => {
  try {
    const res = await uni.getBatteryInfo()
    
    const batteryStatus = res.isCharging ? '充电中 🔌' : '未充电 🔋'
    
    uni.showModal({
      title: '电池状态信息',
      content: `🔋 电池电量：${res.level}%\n📱 充电状态：${batteryStatus}\n\n• 实时电量监控\n• 充电状态检测\n• 低电量提醒`,
      showCancel: false
    })
  } catch (error) {
    showToast('获取电池信息失败')
  }
}

// 测试文件系统
const testFileSystem = async () => {
  try {
    // 简化版文件系统测试，直接使用storage来模拟
    const testData = {
      content: '文件系统测试',
      createTime: new Date().toLocaleString(),
      platform: platformName.value
    }
    
    Storage.set('file_test', testData, 60) // 1分钟过期
    const readData = Storage.get('file_test')
    
    uni.showModal({
      title: '文件系统测试',
      content: `📁 文件操作成功！\n\n文件内容：\n${JSON.stringify(readData, null, 2)}\n\n• 支持文件读写\n• 目录管理\n• 缓存控制`,
      showCancel: false
    })
  } catch (error) {
    showToast('文件操作失败')
  }
}

// 显示TypeScript信息
const showTypeScriptInfo = () => {
  uni.showModal({
    title: 'TypeScript 支持',
    content: `📝 TypeScript 特性：\n• 完整类型定义\n• 智能代码提示\n• 编译时错误检查\n• 重构安全保障\n• 团队协作规范\n\n🎯 已配置：\n• UniApp API类型\n• Vue3 组合式API\n• Pinia状态管理\n• 自定义工具类型`,
    showCancel: false
  })
}

onMounted(() => {
  console.log('Index page mounted')
})
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.status-bar {
  background: transparent;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  
  .navbar-title {
    font-size: 18px;
    font-weight: bold;
    color: white;
  }
  
  .navbar-right {
    .network-status {
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      color: white;
      
      &.network-wifi {
        background: rgba(103, 194, 58, 0.8);
      }
      
      &.network-mobile {
        background: rgba(64, 158, 255, 0.8);
      }
      
      &.network-offline {
        background: rgba(245, 108, 108, 0.8);
      }
    }
  }
}

.content {
  flex: 1;
  padding: 16px;
}

.welcome-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  text-align: center;
  
  .welcome-title {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }
  
  .welcome-subtitle {
    font-size: 16px;
    color: #909399;
    margin-bottom: 16px;
  }
  
  .platform-info {
    display: flex;
    justify-content: space-around;
    
    text {
      font-size: 14px;
      color: #606266;
    }
  }
}

.feature-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  
  .feature-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
  }
  
  .feature-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #F2F6FC;
    
    &:last-child {
      border-bottom: none;
    }
    
    .feature-icon {
      font-size: 24px;
      margin-right: 12px;
    }
    
    .feature-content {
      flex: 1;
      
      .feature-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .feature-desc {
        font-size: 14px;
        color: #909399;
      }
    }
    
    .feature-arrow {
      font-size: 16px;
      color: #C0C4CC;
    }
  }
}

.system-info {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  
  .info-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 16px;
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    
    .info-item {
      .info-label {
        display: block;
        font-size: 14px;
        color: #909399;
        margin-bottom: 4px;
      }
      
      .info-value {
        display: block;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
}

.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style> 